<?php

namespace app\agent\model\channel;

use think\facade\Db;
use fast\Random;

/**
 * 话费渠道
 */
class Mobile
{
    private $table = 'agent_channel';

    /**
     * 列表
     */
    public function getList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent']['id']];
        $where[] = ['is_deleted', '=', 0];
        $name = trim($params['name'] ?? '');
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $sortFields = ['total_order_num', 'total_order_amount'];
        if (!empty($params['sortField']) && !empty($params['sortOrder'])) {
            if (in_array($params['sortField'], $sortFields)) {
                if ($params['sortOrder'] == 'ascend') {
                    $order = $params['sortField'] . ' asc';
                } else {
                    $order = $params['sortField'] . ' desc';
                }
            } else {
                $order = 'id desc';
            }
        } else {
            $order = 'id desc';
        }
        $list = Db::name($this->table)
            ->where($where)
            ->order($order)
            ->paginate($paginate)
            ->toArray();
        $agentUrl = env('app.agent_url');
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['url'] = $agentUrl . '/h5/?channel=' . $v['name'];
        }
        $list['mobile_discount_slow'] = $params['agent']['mobile_discount_slow'];
        $list['mobile_discount_fast'] = $params['agent']['mobile_discount_fast'];

        return success('操作成功', $list);
    }

	/**
	 * 添加
	 */
	public function create($params)
	{
        $unique = Db::name($this->table)
            ->where('name', $params['name'])
            ->where('is_deleted', 0)
            ->value('id');
        if ($unique) {
            return fail('该渠道名称已经被占用');
        }
        if ($params['mobile_discount_slow'] < $params['agent']['mobile_discount_slow']) {
            return fail('慢充折扣不能低于 ' . $params['agent']['mobile_discount_slow'] . ' 折');
        }
        if ($params['mobile_discount_fast'] < $params['agent']['mobile_discount_fast']) {
            return fail('快充折扣不能低于 ' . $params['agent']['mobile_discount_fast'] . ' 折');
        }

        if ($params['mobile_status_slow'] != 1 && $params['mobile_status_fast'] != 1) {
            return fail('慢充跟快充不能同时禁用');
        }

        Db::startTrans();
        try {
            $id = Db::name($this->table)
                ->insertGetId([
                    'mobile_discount_slow' => $params['mobile_discount_slow'],
                    'mobile_discount_fast' => $params['mobile_discount_fast'],
                    'mobile_status_slow' => $params['mobile_status_slow'],
                    'mobile_status_fast' => $params['mobile_status_fast'],
                    'agent_id' => $params['agent']['id'],
                    'name' => $params['name'],
                    'remark' => $params['remark'] ?? '',
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('渠道添加失败：' . $e->getMessage());
        }

        return success('添加成功', [
            'id' => intval($id),
        ]);
    }

    /**
     * 编辑
     */
    public function edit($params)
    {
        $exists = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent']['id'])
            ->where('is_deleted', 0)
            ->value('id');
        if (empty($exists)) {
            return fail('渠道不存在');
        }
        if ($params['mobile_discount_slow'] < $params['agent']['mobile_discount_slow']) {
            return fail('话费折扣不能低于 ' . $params['agent']['mobile_discount_slow'] . ' 折');
        }
        if ($params['mobile_discount_fast'] < $params['agent']['mobile_discount_fast']) {
            return fail('话费折扣不能低于 ' . $params['agent']['mobile_discount_fast'] . ' 折');
        }

        if ($params['mobile_status_slow'] != 1 && $params['mobile_status_fast'] != 1) {
            return fail('慢充跟快充不能同时禁用');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $params['id'])
                ->update([
                    'mobile_discount_slow' => $params['mobile_discount_slow'],
                    'mobile_discount_fast' => $params['mobile_discount_fast'],
                    'mobile_status_slow' => $params['mobile_status_slow'],
                    'mobile_status_fast' => $params['mobile_status_fast'],
                    'remark' => $params['remark'] ?? '',
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('渠道更新失败：' . $e->getMessage());
        }

        return success('更新成功', [
            'id' => intval($params['id']),
        ]);
    }

    /**
     * 删除
     */
    public function delete($params)
    {
        if (empty($params['id'])) {
            return fail('参数有误');
        }
        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent']['id'])
            ->where('is_deleted', 0)
            ->find();
        if (empty($info))  {
            return success('删除成功');
        }

        if ($info['total_order_num'] > 0) {
            return fail('该渠道有产生订单，无法删除');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $info['id'])
                ->update([
                    'is_deleted' => 1,
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('删除失败: ' . $e->getMessage());
        }

        return success('删除成功');
    }
}
